﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace HobSoft.SoccerBet2014.Common.Wpf.Converter
{
    public class KeyGestureValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var gesture = value as KeyGesture;
            if (gesture == null)
                return "未绑定";
            return gesture.DisplayString;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var text = value as string;
            if (string.IsNullOrEmpty(text)) return null;
            var gestures = text.Split('+');
            var key = Key.None;
            var modifierKey = ModifierKeys.None;
            if (gestures.Length == 1)
            {
                Enum.TryParse<Key>(gestures[0], out key);
            }
            else if (gestures.Length > 1)
            {
                Enum.TryParse<Key>(gestures[gestures.Length - 1], out key);
                for (int i = 0; i < gestures.Length - 2; i++)
                {
                    switch (gestures[i].ToUpper())
                    {
                        case "CTRL":
                            modifierKey = modifierKey | ModifierKeys.Control;
                            break;
                        case "SHIFT":
                            modifierKey = modifierKey | ModifierKeys.Shift;
                            break;
                        case "ALT":
                            modifierKey = modifierKey | ModifierKeys.Alt;
                            break;
                        default:
                            break;
                    }
                }
            }
            return new KeyGesture(key, modifierKey, text);
        }
    }
}
